<template>
  <view>
    <!-- 日期选择器 -->
    <view class="content" :style="cssVars">
      <view class="calendar-wrapper">
        <!-- 选择月份 -->
        <view class="header" v-if="headerBar">
          <view class="iconfont iconarrow-left-bold pre" @click="changeMonth('pre')">{{
            perMonth
          }}</view>
          <view>{{ y + '年' + formatNum(m) + '月' }}</view>
          <view class="iconfont iconarrow-left-bold-copy next" @click="changeMonth('next')">{{
            nextMonth
          }}</view>
        </view>
        <!-- 星期栏 -->
        <view class="week">
          <view class="week-day" v-for="(item, index) in weekDay" :key="index">{{ item }}</view>
        </view>
        <view class="uni-margin-wrap">
          <swiper class="swiper" @change="_onClickSlideApi" duration="200" circular :style="{ height: height }">
            <swiper-item v-for="(calendar, indexa) in 3" :key="indexa" :style="{ height: height }">
              <view class="swiper-item uni-bg-red" :style="{ height: height }">
                <view class="content" :style="{ height: height }">
                  <view :style="{ top: positionTop + 'rpx' }" class="days">
                    <view class="item" v-for="(item, index) in dates" :key="index">
                      <view v-if="!isSelectOne" class="day" @click="selectOne(item, $event)" :class="{
                        choose:
                          getActday(`${item.year}-${item.month}-${item.date}`) && item.isCurM, //选中的日期
                        chooseMarkDay: getChoose(`${item.year}-${item.month}-${item.date}`),
                        nolm: !item.isCurM, //不在本月的日
                        today: isToday(item.year, item.month, item.date) && isMsgInfo, //当日日期
                        endDayStyle: isEndDay(item.year, item.month, item.date) && isCurrentDay,
                        isSleep: isSleep(`${item.year}-${item.month}-${item.date}`), //是否睡眠
                        isXq: isXq(`${item.year}-${item.month}-${item.date}`), //是否小憩
                        isDisabled: isDisabled(`${item.year}-${item.month}-${item.date}`), //是否可选
                        isFood: isFood(`${item.year}-${item.month}-${item.date}`), //记录饮食
                      }">
                        <view>{{ Number(item.date) }}</view>
                        <view class="iconBox">
                          <image
                            src="https://ossresource.miyingbl.com/uploads/20240509/102710906766443a89afa52ff3e6ba23.png"
                            class="icon sleepIcon"></image>
                          <image
                            src="https://ossresource.miyingbl.com/uploads/20240509/377b85eaf409fb8b95b98af09f00cb52.png"
                            class="icon qiIcon"></image>
                        </view>
                      </view>
                      <view v-else class="day" @click="selectOne(item, $event)" :class="{
                        choose:
                          getActday(`${item.year}-${item.month}-${item.date}`) && item.isCurM, //选中的日期
                        chooseMarkDay: getChoose(`${item.year}-${item.month}-${item.date}`),
                        nolm: !item.isCurM, //不在本月的日
                        todayC: isToday(item.year, item.month, item.date) && isMsgInfo, //当日日期
                        isSleep: isSleep(`${item.year}-${item.month}-${item.date}`), //是否睡眠
                        isXq: isXq(`${item.year}-${item.month}-${item.date}`), //是否小憩
                        isDisabled: isDisabled(`${item.year}-${item.month}-${item.date}`), //是否可选
                        isFood: isFood(`${item.year}-${item.month}-${item.date}`), //记录饮食
                      }">
                        <view>{{ Number(item.date) }}</view>
                        <view class="iconBox">
                          <image
                            src="https://ossresource.miyingbl.com/uploads/20240509/102710906766443a89afa52ff3e6ba23.png"
                            class="icon sleepIcon"></image>
                          <image
                            src="https://ossresource.miyingbl.com/uploads/20240509/377b85eaf409fb8b95b98af09f00cb52.png"
                            class="icon qiIcon"></image>
                        </view>
                      </view>
                      <view class="iconfont iconyixuanzhong"
                        :class="{ markDays: getChoose(`${item.year}-${item.month}-${item.date}`) }" v-if="getChoose(`${item.year}-${item.month}-${item.date}`) &&
                          !isMarkDay(item.year, item.month, item.date) &&
                          item.isCurM
                          ">
                      </view>
                    </view>
                  </view>
                </view>
              </view>
            </swiper-item>
          </swiper>
        </view>
        <!-- 日历数字 -->

        <view class="footer">
          <view class="legendBox">
            <view v-for="(item, index) in legend" :key="index" class="legendItem" v-show="legend.length > 0">
              <image :src="item.icon" class="icon"> </image> <text>{{ item.name }}</text>
            </view>
          </view>
          <view>
            <view class="backBtn" :style="{ background: backBgColor }" :class="{
              notToday:
                (choose.length > 0 && choose != today && isMsgInfo && !isCurrentDay) ||
                y != currentY && isMsgInfo ||
                m != currentM && isMsgInfo,
            }" @click="backtoday()">{{ backtodayText }}</view>
          </view>
        </view>
      </view>
    </view>
  </view>
</template>
<script>
export default {
  props: {
    // 星期几为第一天(0为星期日)
    weekstart: {
      type: Number,
      default: 0,
    },
    // 标记的日期
    markDays: {
      type: Array,
      default: () => {
        return []
      },
    },
    //是否展示月份切换按钮
    headerBar: {
      type: Boolean,
      default: true,
    },
    //过去日期是否不可点击
    disabledAfter: {
      type: Boolean,
      default: false,
    },
    isMsgInfo: {
      type: Boolean,
      default: true,
    },
    isCurrentDay: {
      type: Boolean,
      default: false,
    },
    //接收用户选择的参数
    actDay: {
      type: Array,
      default: [],
    },
    //接受已经被选择的参数
    chooseDay: {
      type: Array,
      default: [],
    },
    legend: {
      type: Array,
      default: [],
    },
    endTime: {
      type: String,
      default: '',
    },
    startTime: {
      type: String,
      default: '',
    },
    lightBgColoor: {
      type: String,
      default: '#EEE9FF',
    },
    textColor: {
      type: String,
      default: 'linear-gradient(180deg, #cb9fff 0%, #a28aff 100%)',
    },
    backtodayText: {
      type: String,
      default: '回今天'
    },
    backBgColor: {
      type: String,
      default: '#c0c0c0'
    }
  },
  data() {
    return {
      weektext: ['日', '一', '二', '三', '四', '五', '六'],
      y: new Date().getFullYear(), // 年
      m: new Date().getMonth() + 1, // 月
      d: new Date().getDate(), //日
      currentY: new Date().getFullYear(),
      currentM: new Date().getMonth() + 1,
      dates: [], // 当前月的日期数据
      positionTop: 0,
      choose: '',
      chooseArr: [],
      today: '',
      slideDataListIndex: 0,
      perMonth: '',
      nextMonth: '',
      isSelectOne: false,
    }
  },
  created() {
    this.dates = this.monthDay(this.y, this.m)
    this.perMonth = this.setPreMonth(this.y, this.m)
    this.nextMonth = this.setNextMonth(this.y, this.m)
  },
  mounted() {
    // this.choose = this.getToday().date;
  },
  computed: {
    // 顶部星期栏
    weekDay() {
      return this.weektext.slice(this.weekstart).concat(this.weektext.slice(0, this.weekstart))
    },
    height() {
      return (this.dates.length / 7) * 90 + 20 + 'rpx'
    },

    cssVars() {
      return {
        "--varLightBgColoor": this.lightBgColoor,
        "--varTextColor": this.textColor
      };
    }
  },
  methods: {
    // 是否睡眠
    isSleep(day) {
      let flag = false
      for (let i = 0; i < this.chooseDay.length; i++) {
        if (day == this.chooseDay[i]?.date && this.chooseDay[i]?.is_sleep) {
          flag = true
          break
        }
      }
      return flag
    },
    isXq(day) {
      let flag = false
      for (let i = 0; i < this.chooseDay.length; i++) {
        if (day == this.chooseDay[i]?.date && this.chooseDay[i]?.is_resting) {
          flag = true
          break
        }
      }
      return flag
    },
    isDisabled(day) {
      if (new Date(day) > new Date(this.endTime) || new Date(day) < new Date(this.startTime)) {
        return true
      } else {
        return false
      }
      // if()
    },
    // 是否记录饮食
    isFood(day) {
      let flag = false
      for (let i = 0; i < this.chooseDay.length; i++) {
        if (day == this.chooseDay[i]?.data && this.chooseDay[i]?.food) {
          flag = true
          break
        }
      }
      return flag
      // if()
    },
    //已被投标的日期
    getChoose(day) {
      for (let i = 0; i < this.chooseDay.length; i++) {
        if (day == this.chooseDay[i]) {
          return true
        }
      }
    },
    //用户选择的日期
    getActday(day) {
      if (day == this.choose) {
        return true
      }
    },
    formatNum(num) {
      let res = Number(num)
      return res < 10 ? '0' + res : res
    },
    getToday() {
      let date = new Date()
      let y = date.getFullYear()
      let m = date.getMonth()
      let d = date.getDate()
      let week = new Date().getDay()
      let weekText = ['日', '一', '二', '三', '四', '五', '六']
      let formatWeek = '星期' + weekText[week]
      let today = {
        date: y + '-' + this.formatNum(m + 1) + '-' + this.formatNum(d),
        week: formatWeek,
      }
      this.today = y + '-' + this.formatNum(m + 1) + '-' + this.formatNum(d)
      return today
    },
    // 获取当前月份数据
    monthDay(y, month) {
      let dates = []
      let m = Number(month)
      let firstDayOfMonth = new Date(y, m - 1, 1).getDay() // 当月第一天星期几
      let lastDateOfMonth = new Date(y, m, 0).getDate() // 当月最后一天
      let lastDayOfLastMonth = new Date(y, m - 2, 0).getDate() // 上一月的最后一天
      let weekstart = this.weekstart == 7 ? 0 : this.weekstart
      let startDay = (() => {
        // 周初有几天是上个月的
        if (firstDayOfMonth == weekstart) {
          return 0
        } else if (firstDayOfMonth > weekstart) {
          return firstDayOfMonth - weekstart
        } else {
          return 7 - weekstart + firstDayOfMonth
        }
      })()
      let endDay = 7 - ((startDay + lastDateOfMonth) % 7) // 结束还有几天是下个月的
      for (let i = 1; i <= startDay; i++) {
        dates.push({
          date: this.formatNum(lastDayOfLastMonth - startDay + i),
          day: weekstart + i - 1 || 7,
          month: m - 1 >= 0 ? this.formatNum(m - 1) : 12,
          year: m - 1 >= 0 ? y : y - 1,
        })
      }
      for (let j = 1; j <= lastDateOfMonth; j++) {
        dates.push({
          date: this.formatNum(j),
          day: (j % 7) + firstDayOfMonth - 1 || 7,
          month: this.formatNum(m),
          year: y,
          isCurM: true, //是否当前月份
        })
      }
      if (endDay < 7) {
        for (let k = 1; k <= endDay; k++) {
          dates.push({
            date: this.formatNum(k),
            day: (lastDateOfMonth + startDay + weekstart + k - 1) % 7 || 7,
            month: m + 1 <= 11 ? this.formatNum(m + 1) : 0,
            year: m + 1 <= 11 ? y : y + 1,
          })
        }
      }

      // console.log(dates); //日期
      return dates
    },
    isWorkDay(y, m, d) {
      //是否工作日
      let ymd = `${y}/${m}/${d}`
      let formatDY = new Date(ymd.replace(/-/g, '/'))
      let week = formatDY.getDay()
      if (week == 0 || week == 6) {
        return false
      } else {
        return true
      }
    },
    isFutureDay(y, m, d) {
      //是否未来日期
      let ymd = `${y}/${m}/${d}`
      let formatDY = new Date(ymd.replace(/-/g, '/'))
      let showTime = formatDY.getTime()
      let curTime = new Date().getTime()
      if (showTime > curTime) {
        return true
      } else {
        return false
      }
    },
    // 标记日期
    isMarkDay(y, m, d) {
      let flag = false
      for (let i = 0; i < this.markDays.length; i++) {
        let dy = `${y}-${m}-${d}`
        if (this.markDays[i] == dy) {
          flag = true
          break
        }
      }
      return flag
    },
    isToday(y, m, d) {
      let checkD = y + '-' + m + '-' + d
      let today = this.getToday().date
      if (checkD == today) {
        return true
      } else {
        return false
      }
    },
    isEndDay(y, m, d) {
      let checkD = y + '-' + m + '-' + d
      let today = this.endTime
      console.log(today)
      if (checkD == today) {
        return true
      } else {
        return false
      }
    },
    // 点击回调
    selectOne(i, event) {
      let changeDay = `${i.year}-${i.month}-${i.date}`
      console.log(changeDay == this.getToday().date)
      if (changeDay == this.getToday().date) {
        this.isSelectOne = false
      } else {
        this.isSelectOne = true
      }
      let date = `${i.year}-${i.month}-${i.date}`

      let selectD = new Date(date).getTime()
      let curTime = new Date().getTime() //当前时间
      let endTime = new Date(this.endTime).getTime() //结束时间
      let startTime = new Date(this.startTime).getTime() //结束时间
      let week = new Date(date).getDay()
      let weekText = ['日', '一', '二', '三', '四', '五', '六']
      let formatWeek = '星期' + weekText[week]
      let response = {
        date: date,
        week: formatWeek,
      }
      if (selectD > endTime) {
        return false
      }
      if (selectD < startTime) {
        return false
      }
      if (selectD < curTime) {
        if (this.disabledAfter) {
          console.log('过去日期不可选')
          return false
        } else {
          this.choose = date
          this.$emit('onDayClick', response)
        }
      } else {
        this.choose = date
        this.chooseArr.push(date)
        this.$emit('onDayClick', response)
      }
      // console.log(response);
    },
    //改变年月
    changYearMonth(y, m) {
      this.dates = this.monthDay(y, m)
      this.y = y
      this.m = m
    },
    setPreMonth(cy, cm) {
      console.log(cy)
      let y
      let m
      if (cm + 1 == 2) {
        m = 12
        y = cy - 1
      } else {
        m = cm - 1
        y = cy
      }
      return `${y}年${m}月`
    },
    setNextMonth(cy, cm) {
      let y
      let m
      if (cm + 1 == 13) {
        m = 1
        y = cy + 1
      } else {
        m = cm + 1
        y = cy
      }
      return `${y}年${m}月`
    },
    changeMonth(type) {
      if (type == 'pre') {
        if (this.m + 1 == 2) {
          this.m = 12
          this.y = this.y - 1
        } else {
          this.m = this.m - 1
        }
      } else {
        if (this.m + 1 == 13) {
          this.m = 1
          this.y = this.y + 1
        } else {
          this.m = this.m + 1
        }
      }

      this.perMonth = this.setPreMonth(this.y, this.m)
      this.nextMonth = this.setNextMonth(this.y, this.m)
      this.dates = this.monthDay(this.y, this.m)
      let currentDate = `${this.y}-${this.m}`
      this.$emit('onMonthChange', {
        momth: currentDate,
      })
    },
    backtoday() {
      this.isSelectOne = false
      this.m = this.currentM
      this.y = this.currentY
      this.perMonth = this.setPreMonth(this.y, this.m)
      this.nextMonth = this.setNextMonth(this.y, this.m)
      this.dates = this.monthDay(this.currentY, this.currentM)
      this.choose = ''
      this.$emit('onBacktoday', {})
    },
    _onClickSlideApi(e) {
      let current = e.detail.current

      let oldIndex = this.slideDataListIndex
      let curr = e.detail.current
      this.slideDataListIndex = current
      if (current - oldIndex == 1 || current - oldIndex == -2) {
        this.changeMonth('next')
      } else {
        this.changeMonth('pre')
      }
    },
  },
}
</script>
<style lang="scss">
.content {
  .content_box {}

  // .popup_body {
  // height: 800rpx;
  // border-radius: 20rpx 20rpx 0 0;
  // background-color: #fff;

  // .close_popup {
  // 	display: flex;
  // 	flex-direction: row-reverse;
  // 	padding: 20rpx;

  // 	.iconfont {
  // 		font-size: 36rpx;
  // 	}
  // }

  .calendar-wrapper {
    color: #6f6d6d;
    font-size: 28rpx;
    text-align: center;
    // background-color: #fff;
    // padding-bottom: 10rpx;
    // border-radius: 20rpx;

    .header {
      display: flex;
      align-items: center;
      justify-content: space-between;
      height: 90rpx;
      color: #42464a;
      font-weight: 500;
      border-bottom: 2rpx solid #f2f2f2;
      background: var(--varLightBgColoor);
      font-size: 36rpx;
      color: #000000;
      line-height: 90rpx;
      text-align: left;
      box-sizing: border-box;
      width: 100%;
      overflow: hidden;

      .pre,
      .next {
        font-size: 24rpx;
        // padding: 8rpx 15rpx;
        // border-radius: 10rpx;
        // border: 2rpx solid #dcdfe6;
      }

      .pre {
        margin-left: -45rpx;
        text-transform: none;
        background: linear-gradient(-90deg, #666666 0%, rgba(204, 204, 204, 0) 100%);

        -webkit-background-clip: text;
        /*将设置的背景颜色限制在文字中*/
        -webkit-text-fill-color: transparent;
        /*给文字设置成透明*/
      }

      .next {
        margin-right: -45rpx;
        text-transform: none;
        background: linear-gradient(90deg, #666666 0%, rgba(204, 204, 204, 0) 100%);
        -webkit-background-clip: text;
        /*将设置的背景颜色限制在文字中*/
        -webkit-text-fill-color: transparent;
        /*给文字设置成透明*/
      }
    }

    .week {
      display: flex;
      align-items: center;
      border-bottom: 1rpx solid rgba(255, 255, 255, 0.2);
      font-size: 36rpx;
      color: #333333;
      padding: 0 30rpx;
      box-sizing: border-box;

      view {
        flex: 1;
        padding: 30rpx 0;
      }
    }

    .content {
      position: relative;
      overflow: hidden;
      transition: height 0.4s ease;
      padding: 0 30rpx;
      box-sizing: border-box;

      .days {
        transition: top 0.3s;
        display: flex;
        align-items: center;
        flex-wrap: wrap;

        .item {
          position: relative;
          display: block;
          height: 90rpx;
          line-height: 90rpx;
          width: calc(100% / 7);

          .day {
            font-style: normal;
            display: inline-block;
            vertical-align: middle;
            width: 53rpx;
            height: 53rpx;
            line-height: 53rpx;
            // overflow: hidden;
            border-radius: 53rpx;
            font-weight: 800;
            color: #333;

            &.chooseMarkDay {
              //已被投标的日期
              // background-color: #43a761;
              color: #5b5b5b;
            }

            &.nolm {
              color: #fff;
              opacity: 0;
            }
          }

          .iconBox {
            width: 53rpx;
            display: flex;
            align-items: center;
            justify-content: center;
          }

          .icon {
            width: 13rpx;
            height: 13rpx;
            display: none;
          }

          .isSleep {
            .sleepIcon {
              display: block;
            }
          }

          .isXq {
            .qiIcon {
              display: block;
              width: 15rpx;
              height: 15rpx;
            }
          }

          .isWorkDay {
            color: #25272a;
          }

          .isDisabled {
            color: #c6c7c7;
          }

          .notSigned {
            font-style: normal;
            width: 8rpx;
            height: 8rpx;
            background: #fa7268;
            border-radius: 10rpx;
            position: absolute;
            left: 50%;
            bottom: 0;
            pointer-events: none;
          }

          .choose {
            // background-color: #4bcdc4;
            background: #fdba55;
            color: #fff;
            font-weight: 500;
          }

          .isFood {

            // position: relative;
            &::after {
              position: absolute;
              content: '';
              left: 0;
              right: 0;
              bottom: 0px;
              width: 8rpx;
              height: 8rpx;
              background: #fdba55;
              border-radius: 50%;
              margin: auto;
            }
          }

          .today {
            color: #fff;
            font-weight: 500;
            // background-color: #a0eac1;
            background: var(--varTextColor);

            &.isFood {

              // position: relative;
              &::after {
                position: absolute;
                content: '';
                left: 0;
                right: 0;
                bottom: 0px;
                width: 8rpx;
                height: 8rpx;
                background: var(--varTextColor);
                border-radius: 50%;
                margin: auto;
              }
            }
          }

          .todayC {
            color: var(--varTextColor);
            font-weight: 600;
            // background-color: #a0eac1;
            background: #fff;

            &.isFood {

              // position: relative;
              &::after {
                position: absolute;
                content: '';
                left: 0;
                right: 0;
                bottom: 0px;
                width: 8rpx;
                height: 8rpx;
                background: var(--varTextColor);
                border-radius: 50%;
                margin: auto;
              }
            }
          }

          .endDayStyle {
            background: #fdba55;
            color: #fff;
            font-weight: 500;

            &.isFood {

              // position: relative;
              &::after {
                position: absolute;
                content: '';
                left: 0;
                right: 0;
                bottom: 0px;
                width: 8rpx;
                height: 8rpx;
                background: #fdba55;
                border-radius: 50%;
                margin: auto;
              }
            }
          }

          .workDay {
            font-style: normal;
            width: 8rpx;
            height: 8rpx;
            background: #4d7df9;
            border-radius: 10rpx;
            position: absolute;
            left: 50%;
            bottom: 0;
            pointer-events: none;
          }

          .markDays {
            font-style: normal;
            position: absolute;
            top: 2rpx;
            right: 11rpx;
            pointer-events: none;
            font-size: 80rpx;
            color: rgba(160, 234, 193, 0.5);
          }
        }
      }
    }
  }

  // }
}

.footer {
  display: flex;
  align-items: center;
  padding: 0 24rpx;
  margin-top: 30rpx;

  .legendBox {
    flex: 1;
    display: flex;
    align-items: flex-end;

    text {
      font-weight: 500;
      font-size: 24rpx;
      color: #666666;
      padding-left: 5rpx;
    }

    .legendItem {
      display: flex;
      align-items: center;
      margin-right: 20rpx;
    }

    .icon {
      width: 24rpx;
      height: 25rpx;
      display: block;
    }
  }

  .backBtn {
    padding: 0 40rpx;
    height: 78rpx;
    border-radius: 40rpx;
    text-align: center;
    line-height: 78rpx;
    font-family: PingFang SC, PingFang SC;
    font-weight: 400;
    font-size: 30rpx;
    color: #ffffff;
    background: #c0c0c0;

    &.notToday {
      background: var(--varTextColor) !important;
    }
  }
}

.swiper {}

.swiper-item {
  display: block;
  text-align: center;
}
</style>

